package com.daon.filter;

import com.daon.common.Const;
import com.daon.common.RequestHolder;
import com.daon.pojo.SysUser;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 1daon
 * @EMAIL 532418116@qq.com
 * @Version 创建时间：2018/3/25 下午3:22
 * @Modified By
 */
public class LoginFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        if(req.getRequestURI().indexOf("login") <= 0) {
            SysUser sysUser = (SysUser) req.getSession().getAttribute(Const.CURRENT_USER_INFO);
            if (sysUser == null) {
                String t = req.getParameter("t");
                if(StringUtils.isNotBlank(t)){
                    //针对页面请求处理
                    String path = "/sys/login/relogin.page";
                    resp.sendRedirect(path);
                }else{
                    String path = "/sys/login";
                    resp.sendRedirect(path);
                }
                return;
            }
            RequestHolder.add(sysUser);
            RequestHolder.add(req);
        }
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    public void destroy() {

    }
}
